import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup} from "@angular/forms";
import {SystemService} from "../system.service";
import {StorageService} from "../../services/storage.service";
import {ConfirmationService} from "primeng/primeng";

@Component({
  selector: 'app-role-edit',
  templateUrl: './role-edit.component.html',
  styleUrls: ['./role-edit.component.css']
})
export class RoleEditComponent implements OnInit {
  display;
  title;
  role: FormGroup;
  @Output() closeRoleEdit =new EventEmitter();
  @Output() addRole = new EventEmitter(); //新增角色
  @Output() updateRole = new EventEmitter(); //修改角色
  @Input() currentOrg;
  @Input() state;
  submitAddRole = {//新增角色参数
    "rid": '',
    "name": '',
    "remark": '',
    "oid": ''
  };
  submitUpdateRole = [//修改角色参数
    {
      "rid": '',
      "name": '',
      "remark": '',
      "oid": ''
    }
  ]

  constructor(
    private systemService: SystemService,
    private storageService: StorageService,
    private fb: FormBuilder,
    private confirmationService: ConfirmationService
  ) {
    this.role = fb.group({
      rid: [''],
      name: [''],
      remark: [''],
    })
  }

  ngOnInit() {
    this.display = true;
    // console.log(this.currentOrg)
    if(this.state == 'add'){
      this.title = '新增角色';
      this.submitAddRole.oid = this.currentOrg.oid;
      //获取角色id
      this.systemService.getRoleId(this.currentOrg.oid).subscribe(data => {
        // console.log(data);
        this.submitAddRole.rid = data;
      })
    }else{
      this.title = '修改角色';
      this.submitUpdateRole[0].oid = this.currentOrg.oid;
      this.submitUpdateRole[0].rid = this.currentOrg.rid;
    }
  }

  //确定
  formSubmit(bool){
    if(this.state ==='add'){
      this.submitAddRole.name = this.role.value.name;
      this.submitAddRole.remark = this.role.value.remark;
      this.addRoleNode(bool);
    }else{
      this.submitUpdateRole[0].name = this.role.value.name;
      this.submitUpdateRole[0].remark = this.role.value.remark;
      this.updateRoleNode(bool);
    }
  }

  //新增角色
  addRoleNode(bool){
    this.systemService.addRole(this.submitAddRole).subscribe(()=>{
      this.addRole.emit(bool);
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  }

  //修改角色
  updateRoleNode(bool){
    this.systemService.updateRole(this.submitUpdateRole).subscribe(()=>{
      this.updateRole.emit(this.currentOrg);
      this.closeRoleEdit.emit(bool);
    })
  }

  closeRoleEditMask(bool){
    this.closeRoleEdit.emit(bool);
  }

}
